package com.lx.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import Tools.EncodingTool;

import com.lx.biz.IDept;
import com.lx.domain.Dept;
import com.lx.domain.User;

@Controller
public class DeptCon {
	@Resource
	private IDept iDeptimpl ;
	
		
	@RequestMapping(value="dept/deptlist")
	
	public String getAllDept(String deptName, HttpServletRequest request ){ 

		User user = (User)request.getSession().getAttribute("user") ;
		
		if (user==null) {
			return "forward:../login";	
		}
		else if(user.getRole() > 0) {
		request.setAttribute("user",user); 
		if (deptName==null||deptName.equals("")) {
		   request.setAttribute("deptlist",iDeptimpl.geteDepts(deptName));
		}else {
			String dNameString = EncodingTool.encodeStr(deptName);
			request.setAttribute("deptlist",iDeptimpl.geteDepts(dNameString)); 
		}
		 
	    return "dept/deptlist";
		}else {
			return "forward:../login";	
		}
	}  
	
	@RequestMapping("dept/deptlist1")    // //ajax修改测试
	public String getAllDept1(String dept_id, HttpServletRequest request ){ 
		request.setAttribute("deptlist",iDeptimpl.geteDepts(dept_id));  
	    return "dept/deptlist1";  
	}  
	
	@RequestMapping("/deldept")
	public String deldept(String dept_id, HttpServletRequest request){
		Dept dept1 = iDeptimpl.findDept(dept_id);
		String result = null ;
		try { iDeptimpl.delete(dept_id);
		    result = dept1.getDeptName() + "删除成功" ;
		} catch (Exception e) {
		    result = dept1.getDeptName() + "删除失败" ;
		}
		request.setAttribute("result", result);
		return "index" ;
	}
	
	@RequestMapping("/insertdept")
	public String insertdept(Dept dept,HttpServletRequest request){
		String result = null;
		try {iDeptimpl.insert(dept);
		    result =dept.getDeptName() + "添加成功"	;
		} catch (Exception e) {
		    result =dept.getDeptName() + "添加失败"	;
		}
		request.setAttribute("result", result);
		return "index" ;
	}
	
	
	@RequestMapping(value="dept/updatedept" ,produces = "text/html;charset=UTF-8")  //解决result传参String显示为？的方法   produces = "text/html;charset=UTF-8"
	public @ResponseBody String updatedept(Dept dept,HttpServletRequest request){
		try {
			iDeptimpl.update(dept);
			return "success" ;
		} catch (Exception e) {
			return "faile" ;
		}
		
	}
	
	
	@RequestMapping("dept/editdept")
	public String editdept(String id,HttpServletRequest request){
		Dept dept = iDeptimpl.findDept(id);
		request.setAttribute("dept", dept);
		return "dept/editdept" ;
	}
}
